Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

Writing Simple JMS Client Applications

This section shows how to create, package, and run simple JMS client programs packaged as standalone J2EE application clients. These clients access a server based on J2EE technology ("J2EE server"). The clients demonstrate the basic tasks that a JMS application must perform:

In a J2EE application, some of these tasks are performed, in whole or in part, by the container. If you learn about these tasks, you will have a good basis for understanding how a JMS application works on the J2EE platform.

The section covers the following topics:

Each example uses two programs: one that sends messages and one that receives them. You can run the programs in two terminal windows.

When you write a JMS application to run in a J2EE application, you use many of the same methods in much the same sequence as you do for a standalone application client. However, there are some significant differences. Using the JMS API in a J2EE Application describes these differences, and the next chapter provides examples that illustrate them.

Setting Your Environment for Running Applications

Before you can run the examples, you need to ensure that your environment is set appropriately. Table 20-3 shows how to set the environment variables needed to run J2EE applications on Microsoft Windows and UNIX platforms.

Table 20-3 Environment Settings for Compiling and Running J2EE Applications
Platform
Variable Name
Values
Microsoft Windows
%JAVA_HOME%
Directory in which the Java 2 SDK, Standard Edition, version 1.4, is installed
%PATH%
Include <J2EE_HOME>\bin
UNIX
$JAVA_HOME
Directory in which the Java 2 SDK, Standard Edition, version 1.4, is installed
$PATH
Include <J2EE_HOME>/bin

When you install the tutorial, a build.properties file is created in the directory <INSTALL>/j2eetutorial14/. In this file, the property j2ee.home is set to the location of your J2EE Application Server installation.

The examples for this section are in the following directory:

<INSTALL>/j2eetutorial14/examples/jms/simple/ 

A Simple Example of Synchronous Message Receives

This section describes the sending and receiving programs in an example that uses the receive method to consume messages synchronously. This section then explains how to compile, package, and run the programs, using the J2EE 1.4 Application Server.

The following sections describe the steps in creating and running the example:

Writing the Client Programs

The sending program, SimpleProducer.java, performs the following steps:

  1. Performs a JNDI lookup of the ConnectionFactory and Destination:
  2. /*
    * Create a JNDI API InitialContext object if none exists
    * yet.
    */
    try {
      jndiContext = new InitialContext();
    } catch (NamingException e) {
      System.out.println("Could not create JNDI API " +
        "context: " + e.toString());
      System.exit(1);
    }

    /*
    * Look up connection factory and destination. If either
    * does not exist, exit. If you look up a
    * TopicConnectionFactory instead of a
    * QueueConnectionFactory, program behavior is the same.
    */
    try {
      connectionFactory = (ConnectionFactory)
      jndiContext.lookup("jms/QueueConnectionFactory");
      if (destType.equals("queue")) {
        dest = (Queue) jndiContext.lookup(destName);
      } else if (destType.equals("topic")) {
        dest = (Topic) jndiContext.lookup(destName);
      } else {
        throw new Exception("Invalid destination type" +
          "; must be queue or topic");
      }
    } catch (Exception e) {
      System.out.println("JNDI API lookup failed: " +
        e.toString());
      System.exit(1);
    }

  3. Creates a Connection and a Session:
  4. connection = connectionFactory.createConnection();
    session = connection.createSession(false,
      Session.AUTO_ACKNOWLEDGE);

  5. Creates a MessageProducer and a TextMessage:
  6. producer = session.createProducer(dest);
    message = session.createTextMessage();

  7. Sends one or more messages to the destination:
  8. for (int i = 0; i < NUM_MSGS; i++) {
      message.setText("This is message " + (i + 1));
      System.out.println("Sending message: " +
        message.getText());
      producer.send(message);
    }

  9. Sends an empty control message to indicate the end of the message stream:
  10. producer.send(session.createMessage());

  11. Closes the connection in a finally block, automatically closing the session and MessageProducer:
  12. } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {}
      }
    }

The receiving program, SimpleSynchConsumer.java, performs the following steps:

  1. Performs a JNDI lookup of the ConnectionFactory and Destination.
  2. Creates a Connection and a Session
  3. Creates a MessageConsumer:
  4. consumer = session.createConsumer(dest);

  5. Starts the connection, causing message delivery to begin:
  6. connection.start();

  7. Receives the messages sent to the destination until the end-of-message-stream control message is received:
  8. while (true) {
      Message m = consumer.receive(1);
      if (m != null) {
        if (m instanceof TextMessage) {
          message = (TextMessage) m;
          System.out.println("Reading message: " +
            message.getText());
        } else {
          break;
        }
      }
    }

  9. Closes the connection in a finally block, automatically closing the session and MessageConsumer.

The receive method can be used in several ways to perform a synchronous receive. If you specify no arguments or an argument of 0, the method blocks indefinitely until a message arrives:

Message m = consumer.receive(); 
Message m = consumer.receive(0); 

For a simple client program, this may not matter. But if you do not want your program to consume system resources unnecessarily, use a timed synchronous receive. Do one of the following:

The SimpleSynchConsumer program uses an indefinite while loop to receive messages, calling receive with a timeout argument. Calling receiveNoWait would have the same effect.

Compiling the Clients

You can compile the examples using the asant tool.

To compile the examples, do the following.

  1. Verify that you have set the environment variables shown in Table 20-3.
  2. In a terminal window, go to the following directory:
  3. <INSTALL>/j2eetutorial14/examples/jms/simple/

  4. Type the following command:
  5. asant build

This command uses the build.xml file in the simple directory to compile all the source files in the directory. The class files are placed in the build directory.

Starting the JMS Provider

When you use the J2EE Application Server, your JMS provider is the Application Server. Start the server as follows:

Creating the JMS Administered Objects for the Simple Examples

If you are in a hurry, you can create the administered objects described in this section by using the following asant target:

asant create-resources 

This target is in the file <INSTALL>/j2eetutorial14/examples/jms/common/targets.xml, so you can use it from any of the JMS examples directories.

To create these objects manually, use the asadmin command. The following commands create two connection factories:

asadmin create-jms-resource --user admin --resourcetype 
javax.jms.QueueConnectionFactory --property 
imqAddressList=localhost jms/QueueConnectionFactory 
asadmin create-jms-resource --user admin --resourcetype 
javax.jms.TopicConnectionFactory --property 
imqAddressList=localhost jms/TopicConnectionFactory 

The following asadmin commands create a queue whose JNDI name is jms/Queue and a topic whose JNDI name is jms/Topic.

asadmin create-jmsdest --user admin --desttype queue 
PhysicalQueue 
asadmin create-jms-resource --user admin --resourcetype 
javax.jms.Queue --property imqDestinationName=PhysicalQueue
jms/Queue 
asadmin create-jmsdest --user admin --desttype topic 
PhysicalTopic 
asadmin create-jms-resource --user admin --resourcetype 
javax.jms.Topic --property imqDestinationName=PhysicalTopic
jms/Topic 

After you create these objects, reconfigure the server, then stop and restart the server:

asant reconfig_common
asadmin stop-domain
asadmin start-domain 

To verify that the destinations and resources have been created, use the following commands:

asadmin list-jmsdest --user admin 
asadmin list-jms-resources --user admin 

Packaging the Clients

In order to run these examples using the J2EE Application Server, you need to package each one in a standalone client JAR file.

First, start the J2EE Deploytool:

Package the SimpleProducer example as follows:

  1. Choose FileRight ArrowNewRight ArrowApplication Client JAR to start the Application Client Wizard.
  2. Select the radio button labeled Create New Stand-Alone AppClient Module.
  3. Click Browse next to the AppClient Location field and navigate to the <INSTALL>/j2eetutorial14/examples/jms/simple/ directory.
  4. Type SimpleProducer in the File Name field.
  5. Type SimpleProducer in the AppClient Display Name field.
  6. Click the Edit button next to the Contents text area.
  7. In the dialog box, locate the build directory. Select SimpleProducer.class from the Available Files tree area and click Add, then OK
  8. In the General screen, select SimpleProducer in the Main Class combo box.
  9. Click Next.
  10. Click Finish.

Package the SimpleSynchConsumer example the same way, except for the following:

Running the Clients

You run the sample programs using the appclient command. Each of the programs takes command-line arguments: a destination name, a destination type, and, for SimpleProducer, a number of messages.

Run the clients as follows.

  1. Run the SimpleProducer program, sending three messages to the queue jms/Queue:
  2. appclient -client SimpleProducer.jar jms/Queue queue 3

    The output of the program looks like this, along with some output from the AppClient container:

    Destination name is jms/Queue, type is queue
    Sending message: This is message 1
    Sending message: This is message 2
    Sending message: This is message 3

    The messages are now in the queue, waiting to be received.

  3. In the same window, run the SimpleSynchConsumer program, specifying the queue name and type:
  4. appclient -client SimpleSynchConsumer.jar jms/Queue queue

    The output of the program looks like this:

    Destination name is jms/Queue, type is queue
    Reading message: This is message 1
    Reading message: This is message 2
    Reading message: This is message 3

  5. Now try running the programs in the opposite order. Run the SimpleSynchConsumer program. It displays the queue name and then appears to hang, waiting for messages.
  6. In a different terminal window, run the SimpleProducer program. When the messages have been sent, the SimpleSynchConsumer program receives them and exits.
  7. Now run the SimpleProducer program using a topic instead of a queue. On a Microsoft Windows system, the command looks like this:
  8. appclient -client SimpleProducer.jar jms/Topic topic 3

    The output of the program looks like this:

    Destination name is jms/Topic, type is topic
    Sending message: This is message 1
    Sending message: This is message 2
    Sending message: This is message 3

  9. Now run the SimpleSynchConsumer program using the topic. On a Microsoft Windows system, the command looks like this:
  10. appclient -client SimpleSynchConsumer.jar jms/Topic topic

    The result, however, is different. Because you are using a topic, messages that were sent before you started the consumer cannot be received. (See Publish/Subscribe Messaging Domain, for details.) Instead of receiving the messages, the program appears to hang.

  11. Run the SimpleProducer program again in another terminal window. Now the SimpleSynchConsumer program receives the messages:
  12. Destination name is jms/Topic, type is topic
    Reading message: This is message 1
    Reading message: This is message 2
    Reading message: This is message 3

A Simple Example of Asynchronous Message Consumption

This section describes the receiving programs in an example that uses a message listener to consume messages asynchronously. This section then explains how to compile and run the programs, using the J2EE 1.4 Application Server.

The following sections describe the steps in creating and running the example:

Writing the Client Programs

The sending program is SimpleProducer.java, the same program used in the example in A Simple Example of Synchronous Message Receives. You may, however, want to comment out the following line of code, where the producer sends a non-text control message to indicate the end of the messages:

producer.send(session.createMessage()); 

An asynchronous consumer normally runs indefinitely. This one runs until the user types the letter q or Q to stop the program, so it does not use the non-text control message.

The receiving program, SimpleAsynchConsumer.java, performs the following steps:

  1. Performs a JNDI lookup of the ConnectionFactory and Destination
  2. Creates a Connection and a Session
  3. Creates a MessageConsumer
  4. Creates an instance of the TextListener class and registers it as the message listener for the MessageConsumer:
  5. listener = new TextListener();
    consumer.setMessageListener(listener);

  6. Starts the connection, causing message delivery to begin
  7. Listens for the messages published to the destination, stopping when the user types the character q or Q:
  8. System.out.println("To end program, type Q or q, " +
      "then <return>");
    inputStreamReader = new InputStreamReader(System.in);
    while (!((answer == 'q') || (answer == 'Q'))) {
      try {
        answer = (char) inputStreamReader.read();
      } catch (IOException e) {
        System.out.println("I/O exception: "
          + e.toString());
      }
    }

  9. Closes the connection, which automatically closes the session and MessageConsumer

The message listener, TextListener.java, follows these steps:

  1. When a message arrives, the onMessage method is called automatically.
  2. The onMessage method converts the incoming message to a TextMessage and displays its content. If the message is not a text message, it reports this fact:
  3. public void onMessage(Message message) {
      TextMessage msg = null;

      try {
        if (message instanceof TextMessage) {
          msg = (TextMessage) message;
          System.out.println("Reading message: " +
            msg.getText());
        } else {
          System.out.println("Message is not a " +
            "TextMessage");
        }
      } catch (JMSException e) {
        System.out.println("JMSException in onMessage(): " +
          e.toString());
      } catch (Throwable t) {
        System.out.println("Exception in onMessage():" +
          t.getMessage());
      }
    }

Compiling the Clients

To compile the example, do the following.

  1. Verify that you have set the environment variables shown in Table 20-3.
  2. Compile the programs if you did not do so before or if you edited SimpleProducer.java as described in Writing the Client Programs:
  3. asant build

Starting the JMS Provider

If you did not do so before, start the J2EE Application Server in another terminal window.

You will use the connection factories and destinations you created in Creating the JMS Administered Objects for the Simple Examples.

Packaging the SimpleAsynchConsumer Client

If you did not do so before, start the J2EE Deploytool.

Package the SimpleAsynchConsumer example as follows:

  1. Choose FileRight ArrowNewRight ArrowApplication Client JAR to start the Application Client Wizard.
  2. Select the radio button labeled Create New Stand-Alone AppClient Module.
  3. Click Browse next to the AppClient Location field and navigate to the <INSTALL>/j2eetutorial14/examples/jms/simple/ directory.
  4. Type SimpleAsynchConsumer in the File Name field.
  5. Type SimpleAsynchConsumer in the AppClient Display Name field.
  6. Click the Edit button next to the Contents text area.
  7. In the dialog box, locate the build directory. Select SimpleAsynchConsumer.class and TextListener.class from the Available Files tree area and click Add, then OK
  8. In the General screen, select SimpleAsynchConsumer in the Main Class combo box.
  9. Click Next.
  10. Click Finish.

If you did not already package the SimpleProducer program, do so by following the instructions in Packaging the Clients.

Running the Clients

As before, you run the sample programs using the appclient command.

Run the clients as follows.

  1. Run the SimpleAsynchConsumer program, specifying the topic jms/Topic and its type.
  2. appclient -client SimpleAsynchConsumer.jar jms/Topic topic

    The program displays the following lines and appears to hang:

    Destination name is jms/Topic, type is topic
    To end program, type Q or q, then <return>

  3. In another terminal window, run the SimpleProducer program, sending three messages. The commands look like this:
  4. appclient -client SimpleProducer.jar jms/Topic topic 3

    The output of the program looks like this:

    Destination name is jms/Topic, type is topic
    Sending message: This is message 1
    Sending message: This is message 2
    Sending message: This is message 3

    In the other window, the SimpleAsynchConsumer program displays the following:

    Destination name is jms/Topic, type is topic
    To end program, type Q or q, then <return>
    Reading message: This is message 1
    Reading message: This is message 2
    Reading message: This is message 3

    If you did not edit SimpleProducer.java, the following line also appears:

    Message is not a TextMessage

  5. Type Q or q to stop the program.
  6. Now run the programs using a queue. In this case, as with the synchronous example, you can run the SimpleProducer program first, because there is no timing dependency between the sender and receiver:
  7. appclient -client SimpleProducer.jar jms/Queue queue 3

    The output of the program looks like this:

    Destination name is jms/Queue, type is queue
    Sending message: This is message 1
    Sending message: This is message 2
    Sending message: This is message 3

  8. Run the SimpleAsynchConsumer program:
  9. appclient -client SimpleAsynchConsumer.jar jms/Queue queue

    The output of the program looks like this:

    Destination name is jms/Queue, type is queue
    To end program, type Q or q, then <return>
    Reading message: This is message 1
    Reading message: This is message 2
    Reading message: This is message 3

  10. Type Q or q to stop the program.

Running JMS Client Programs on Multiple Systems

JMS client programs can communicate with each other when they are running on different systems in a network. The systems must be visible to each other by name--the UNIX host name or the Microsoft Windows computer name--and must both be running the J2EE server. You do not have to install the tutorial on both systems; you can use the tutorial installed on earth if you have access to the file system on earth.

Suppose that you want to run the SimpleProducer program on one system, mars, and the SimpleSynchConsumer program on another system, earth. To do so, follow these steps.

  1. Start the J2EE Application Server on earth.
  2. Start the J2EE Application Server on mars.
  3. On earth, create a QueueConnectionFactory object, using the following asant target:
  4. asant add-local-factory

    This command creates a connection factory named jms/EarthQueueConnectionFactory.

  5. On mars, create a connection factory with the same name that points to the server on earth. Use the following command, replacing sys-name with the name of your remote system:
  6. asadmin create-jms-resource --resourcetype
    javax.jms.QueueConnectionFactory --property
    imqAddressList=
    sys-name jms/EarthQueueConnectionFactory

    You can also use the asant target add-remote-factory.

    If the JMS service on the remote system uses a port number other than the default (7676), use the syntax imqAddressList=sys-name:port-number.

  7. Reconfigure the server:
  8. asant reconfig_common

  9. Stop and restart the server.
  10. To verify that the factories were created, use the following command:
  11. asadmin list-jms-resources --user admin

  12. In each source program, change the line that looks up the connection factory so that it refers to the new connection factory:
  13. connectionFactory = (ConnectionFactory)
      jndiContext.lookup("jms/EarthQueueConnectionFactory");

  14. Recompile the programs:
  15. asant build

  16. Repackage the SimpleProducer and SimpleSynchConsumer programs as described in Packaging the Clients. Name the files ProducerRemote.jar and SynchConsumerRemote.jar if you don't want to overwrite the other JAR files.
  17. Run SimpleProducer on mars:
  18. appclient -client ProducerRemote.jar jms/Queue queue 3

  19. Run SimpleSynchConsumer on earth:
  20. appclient -client SynchConsumerRemote.jar jms/Queue queue

Because both connection factories have the same name, you can run either the producer or the consumer on either system. (Note: A bug in the JMS provider in the J2EE Application Server may cause a runtime failure to create a connection to systems that use the Dynamic Host Configuration Protocol [DHCP] to obtain an IP address.)

For examples showing how to deploy J2EE applications on two different systems, see An Application Example that Consumes Messages from a Remote J2EE Server and An Application Example that Deploys a Message-Driven Bean on Two J2EE Servers.

Deleting the Connection Factory and Stopping the Server

You will need the connection factory jms/EarthQueueConnectionFactory in the next chapter. However, if you wish to delete it, use the following command:

asant delete-factory 

Remember to delete the connection factory on both systems.

You can use the delete-resources target to delete the destinations and connection factories you created in Creating the JMS Administered Objects for the Simple Examples. However, we recommend that you keep them, because they will be used in most of the JMS examples. Once you have created them, they will be available whenever you restart the J2EE Application Server.

Delete the class files for the programs as follows:

asant clean 

If you wish, you can manually delete the client JAR files.

You can stop the J2EE Application Server as well, but you will need it to run the sample programs in the next section.

Divider
Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

All of the material in The J2EE 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.